/**
 * 
 */
package org.cuatrovientos.erp.dao;

import java.util.List;

import org.cuatrovientos.erp.model.Issue;
import org.cuatrovientos.erp.model.IssueType;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.transaction.annotation.Transactional;

/**
 * @author Raquel Valenzuela <raquel_valenzuela@cuatrovientos.es>
 *
 */
public class IssueDAO implements IssueDAOInterface {
	
	private SessionFactory sessionFactory;
	
	/**
	 * returns Hibernate session
	 * @return
	 */
	 private Session getSession () {
		 return sessionFactory.getCurrentSession();
	 }
	 
	 /* selects an issue by id
	  * @param int id
	  */
	@Transactional(readOnly = true)
	public Issue selectById(int id) {
		Issue issue = (Issue) getSession().get(Issue.class, id);
		return issue;
	}

	/*
	 * Selects all issues
	 * 
	 * @return List of issues
	 */
	@Transactional(readOnly = true)
	public List<Issue> selectAll() {
		List<Issue> issues = getSession().createQuery("from issue").list();
		return issues;
	}

	/*
	 * retrieves all issues from db
	 * 
	 * @return List of issueTypes
	 */
	@Transactional(readOnly = true)
	public int selectAllCount() {
		List<Issue> issues = getSession().createQuery("from issue").list();
		return issues.size();
	}

	/*
	 * inserts a new issue in database retrieves generated id and sets to
	 * issueType instance
	 * 
	 * @param new issueType
	 */
	@Override
	public void insert(Issue issue) {
		Integer id = (Integer) getSession().save(issue);
		issue.setId(id);
	}

	/*
	 * updates an issue
	 * 
	 * @param issueType to update
	 */
	@Override
	public void update(Issue issue) {
		getSession().merge(issue);

	}

	/*
	 * Deletes an Issue
	 * 
	 * @param issueType to delete
	 */
	@Override
	public void delete(Issue issue) {
		getSession().delete(issue);

	}

	/*
	 * Delete an issue
	 * 
	 * @param int id of the issue type to delete
	 */
	@Override
	public void deleteById(int id) {
		Issue issue = (Issue) getSession().load(Issue.class, id);
		getSession().delete(issue);

	}

	/*
	 * Returns the Issue with the folowing name
	 * 
	 * @paran String name
	 * 
	 * @return List of Issue types
	 */
	@Override
	public List<Issue> search(String name) {
		Query query = getSession().createQuery("from issue i where i.name like :name");
		query.setParameter("name", "%" + name + "%");
		List<Issue> issues = query.list();

		return issues;
	}

}
